package com.hb.trade.api.im.chat.manager;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hb.core.pojo.im.entity.ChatRecord;
import com.hb.core.pojo.im.entity.ChatRecordContent;
import lombok.Getter;
import lombok.Setter;
import org.fzzn.core.model.user.layim.LayImUser;

@Setter
@Getter
public class ChatRecordContentManager extends ChatRecordContent {

    /**
     * 将当前对象封装为LayimUser对象返回
     *
     * @return
     */
    public LayImUser parseRecordContent() {
        String content = this.getContent();
        if (JSONUtil.isJsonObj(content)) {
            JSONObject recordJSON = JSONUtil.parseObj(content);
            LayImUser imUserRecord =
                    JSONUtil.toBean(recordJSON.getJSONObject("contentData"), LayImUser.class);

            // ID需要设置为发送人ID
            imUserRecord.setId(String.valueOf(this.getFromId()));
            // 设置消息唯一ID用于去除重复
            imUserRecord.setCid(this.getMsgId());
            return imUserRecord;
        }
        return null;
    }

    /**
     * 判断获取聊天记录的查询条件
     * 用于区分群组的聊天记录还是私聊的聊天记录
     *
     * @return
     */
    public QueryWrapper<ChatRecordContent> getWrapper() {
        QueryWrapper<ChatRecordContent> wrapper = ChatRecord.wrapper();
        wrapper.orderByAsc("sort_num");
        // fromId为发送人ID
        Long fromId = this.getFromId();
        Long toId = this.getToId();
        switch (this.getType()) {
            case "friend":
                // toId为接收人ID
                wrapper.eq("from_area_id", fromId).eq("to_id", toId)
                        .or()
                        .eq("from_area_id", toId).eq("to_id", fromId)
                        .comment("查询与好友的聊天记录");
                break;
            case "group":
                // toId为群ID
                wrapper.eq("from_area_id", toId)
                        .comment("查询群组聊天记录");
                break;
            default:
        }
        return wrapper;
    }
}
